//
//  GPSTabBarItem.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/10/15.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit

class GPSTabBarItem: UITabBarItem {

    var index: Int = 0
    
    override var badgeValue: String? {
    
        didSet{
            
            setBadgeViewBackImage()
        }
    }
    
    private func setBadgeViewBackImage() {
        
        let target = self.valueForKeyPath("_target") as! UITabBarController
        
        for tabBarChild in target.tabBar.subviews {
            if tabBarChild.isKindOfClass(NSClassFromString("UITabBarButton")!){
                for tabBarButtonChild in tabBarChild.subviews {
                    if tabBarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!){
                        for badgeViewChild in tabBarButtonChild.subviews {
                            if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!) {
                                var count: UInt32 = 0
                                
                                let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
                                
                                for i in 0..<count {
                                    // 取某一个实例变量
                                    let ivar = ivars[Int(i)]
                                    // 获取ivar的名称
                                    let ivarName = NSString(CString: ivar_getName(ivar), encoding: NSUTF8StringEncoding)
                                    
                                    if ivarName!.isEqualToString("_image"){
                                        badgeViewChild.setValue(UIImage(named: "main_badge"), forKey: (ivarName! as String))
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
